<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.io.*,java.util.*,javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.io.output.*"%>

<%@ page import="org.apache.commons.codec.binary.Base64"%>


<%@ page import="api.IFacade"%>
<%@ page import="p3_entities.*"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.UUID"%>



<%
	File file;
	int maxFileSize = 5000 * 1024;
	int maxMemSize = 5000 * 1024;
	ServletContext context = pageContext.getServletContext();
	String filePath = context.getInitParameter("file-upload");
	if (!filePath.trim().endsWith("\\"))
		filePath = filePath+ "\\";

	// Verify the content type
	String contentType = request.getContentType();
	if ((contentType.indexOf("multipart/form-data") >= 0)) {

		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(maxMemSize);
		// Location to save data that is larger than maxMemSize.
		factory.setRepository(new File(context.getInitParameter("file-upload-temp")));

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum file size to be uploaded.
		upload.setSizeMax(maxFileSize);
		try {
			// Parse the request to get file items.
			List fileItems = upload.parseRequest(request);

			// Process the uploaded file items
			Iterator i = fileItems.iterator();

			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (!fi.isFormField()) {
					// Get the uploaded file parameters
					String fieldName = fi.getFieldName();
					String fileName = fi.getName().trim();
					if (fileName.trim().equals("")){
						out.println("KO");
						return;
					}

					String extension = fileName.substring(fileName.lastIndexOf("."));
					boolean isInMemory = fi.isInMemory();
					long sizeInBytes = fi.getSize();
					
					if (sizeInBytes == 0) {
						out.println("KO");
						return;
					}
					
					// Write the file: filename will be a uuid
					UUID uuid = UUID.randomUUID();
					
					file = new File(filePath + uuid.toString() + extension); 
					
					fi.write(file);
					
					out.println(uuid + extension);
					
					// out.println(new String(Base64.encodeBase64(fi.get())));
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			out.println("KO");
		}
	} else {
		out.println("KO");

	}
%>